package com.sc.web.aop;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.sc.dal.mapper.system.LogMapper;
import com.sc.dal.model.system.Log;
import com.sc.util.data.Common;
import com.sc.web.annotation.SystemLog;
/**
 * 
 * <h1>添加操作日志的切面类</h1> 
 * 
 * @author xujunbao 
 * @version LogInterceptor.java,v0.1 2017年3月13日 上午11:00:14 xujunbao Exp  
 *
 */
@Aspect
@Component
public class LogInterceptor {
	@Autowired
	private LogMapper logMapper;
	@Around("@annotation(com.sc.ifs.spring.SystemLog)")
	public void doService(ProceedingJoinPoint point){
		// 执行方法名
		//String methodName = point.getSignature().getName();
		//String className = point.getTarget().getClass().getSimpleName();
		String member = null;
		Long start = 0L;
		Long end = 0L;
		Long time = 0L;
		String ip = null;
		Map<String, Object> map=null; 
//		try {
//			ip = SecurityUtils.getSubject().getSession().getHost();
//		} catch (Exception e) {
//			ip = "无法获取登录用户Ip";
//		}
//		try {
//			// 登录名
//			member = ((Member)SecurityUtils.getSubject().getSession().getAttribute("member")).getmName();
//			if (Common.isEmpty(member)) {
//				member = "无法获取登录用户信息！";
//			}
//		} catch (Exception e) {
//			member = "无法获取登录用户信息！";
//		}
		try {
			map=getControllerMethodDescription(point);
			// 执行方法所消耗的时间
			start = System.currentTimeMillis();
			point.proceed();
			end = System.currentTimeMillis();
		    time = end - start;
		} catch (Throwable e) {
			throw new RuntimeException(e);
		}
		Log log=new Log();
		log.setActiontime(time.toString());
		log.setDescription((String)map.get("description"));
		log.setMemberIp((String)map.get("ip"));
		log.setMethods((String)map.get("methods"));
		log.setmName(member);
		log.setModule((String)map.get("module"));
		logMapper.insertSelective(log);
	}
	public Map<String, Object> getControllerMethodDescription(JoinPoint joinPoint)  throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		String targetName = joinPoint.getTarget().getClass().getName();
		String methodName = joinPoint.getSignature().getName();
		Object[] arguments = joinPoint.getArgs();
		String ip=null;
		if(request.getHeader("x-forwarded-for")==null){
			ip=request.getRemoteAddr();
		}else{
			ip=request.getHeader("x-forwarded-for");
		}
		map.put("ip",ip );
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
               Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {
               	 map.put("module", method.getAnnotation(SystemLog.class).module());
               	 map.put("methods", method.getAnnotation(SystemLog.class).methods());
               	 String de = method.getAnnotation(SystemLog.class).description();
               	 if(Common.isEmpty(de))de="执行成功!";
               	 map.put("description", de);
                    break;
               }
           }
       }
        return map;
   }
	@AfterThrowing("@annotation(com.sc.ifs.spring.SystemLog)")
	public Object doAfterThrowing(JoinPoint point){
		String member = null;
		//Long start = 0L;
		//Long end = 0L;
		Long time = 0L;
		//String ip = null;
		Map<String, Object> map=null; 
		try {
			map=getControllerMethodDescription(point);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Log log=new Log();
		log.setActiontime(time.toString());
		log.setDescription("执行方法异常");
		log.setMemberIp((String)map.get("ip"));
		log.setMethods((String)map.get("methods"));
		log.setmName(member);
		log.setModule((String)map.get("module"));
		logMapper.insertSelective(log);
		return null;
	}
}
